package com.coder.bike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coder.bike.entity.BikeInfo;
import com.coder.bike.entity.Maintain;
import com.coder.bike.mapper.BikeInfoMapper;
import com.coder.bike.mapper.MaintainMapper;
import com.coder.bike.service.IMaintainService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class MaintainServiceImpl extends ServiceImpl<MaintainMapper, Maintain> implements IMaintainService {
    @Resource
    private BikeInfoMapper bikeInfoMapper;

    @Override
    public Page<Maintain> searchByPage(Page<Maintain> page, Maintain maintain) {
        QueryWrapper<Maintain> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(maintain.getBikeId() != null, "bike_id", maintain.getBikeId());
        queryWrapper.like(maintain.getItems() != null, "items", maintain.getItems());
        queryWrapper.like(maintain.getLocation() != null, "location", maintain.getLocation());
        queryWrapper.le(maintain.getHighStartTime() != null, "start_time", maintain.getHighStartTime());
        queryWrapper.ge(maintain.getLowStartTime() != null, "start_time", maintain.getLowStartTime());
        queryWrapper.le(maintain.getHighCost() != null, "cost", maintain.getHighCost());
        queryWrapper.ge(maintain.getLowCost() != null, "cost", maintain.getLowCost());
        queryWrapper.orderByDesc("start_time");
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public boolean delete(String ids) {
        List<Long> list = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        if (!list.isEmpty()) {
            list.forEach(id -> {
                Maintain maintain = baseMapper.selectById(id);
                if (maintain != null) {
                    // 更新单车最后维护时间为空
                    BikeInfo bikeInfo = bikeInfoMapper.selectByBikeId(maintain.getBikeId());
                    if (bikeInfo != null) {
                        bikeInfo.setLastMaintain(null);
                        bikeInfoMapper.updateById(bikeInfo);
                    }
                }
            });
            return baseMapper.deleteBatchIds(list) > 0;
        }
        return false;
    }
}